package com.cium.aqie.highOrderFunction

import java.lang.StringBuilder

/**
 * @Function: map foreach 遍历, reduce
 * @Author: aqie
 * @Date: 2019/9/2 8:13
 */
fun main() {
    val list = listOf<Int>(1, 2, 3, 4)
    val newList = ArrayList<Int>()
    list.forEach {
        val newElement = it * 2 + 1
        newList.add(newElement)
    }
    newList.forEach(::print)    // 单纯迭代
    newList.map(::print)        // 做映射

    println()
    // it.toDouble()
    val newList2 = list.map (Int::toDouble)
    newList2.forEach(::print)

    println()

    /**
     * .. 代表rangeTo, intRange 集合
     */
    val intRangeList = listOf(
            1..5,
            2..6,
            3..7
    )
    val flatList = intRangeList.flatMap { it }
    // reduce 求和
    println(flatList.reduce{acc,i -> acc + i})

    val flatListString = intRangeList.flatMap { intRange->
        // intRange
        intRange.map { it -> "No.$it " }
    }
    flatListString.forEach(::print)

    println()
    // 1,求完阶乘后的集合, 再打印
    (0..6).map(::factorial).forEach(::print)
    // 2,求完阶乘集合再求和,
    println((0..6).map(::factorial).reduce{acc,i -> acc + i})
    // 3.求完阶乘集合再求和, 再加个初始值
    println((0..6).map(::factorial).fold(6){acc,i -> acc + i})
    // 4. 阶乘和拼接字符串
    println((0..6).map(::factorial).fold(StringBuilder()){acc, i ->
        acc.append(i).append(",")
    })
    // 5. 拼接字符串
    println((0..6).joinToString(","))
    // 6. filter 过滤奇数
    println((0..6).map(::factorial).filter{it % 2 == 1})
    println((0..6).map(::factorial).filter(::isEven))
    // 7. filter 获取奇数位结果
    println((0..6).map(::factorial).filterIndexed(){index,i -> index % 2 == 1})
    // 8. 遇到第一个偶数就停止,取所有奇数
    println((0..6).map(::factorial).takeWhile(::isOdd))
}
/**
 * Reduce 求阶乘
 */
fun factorial(n:Int):Int{
    if (n == 0) return 1
    return (1..n).reduce{acc, i -> acc * i}
}

fun isEven(n:Int):Boolean{
    return n % 2 == 0
}
fun isOdd(n:Int):Boolean{
    return n % 2 == 1
}
